<?php
/**
 * 熙巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 本地附件代理服务 - 解决CORS跨域问题并获取氚云真实文件名
 * 尊重劳动成果是一种美德
 */

// 设置CORS头，允许跨域访问
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: *');

// 处理OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// 获取附件ID
$attachmentId = $_GET['id'] ?? '';

if (empty($attachmentId)) {
    http_response_code(400);
    echo 'Missing attachment ID';
    exit;
}

// 构建H3yunApi附件代理URL（请替换为您的实际域名）
$h3yunApiUrl = 'https://your-domain.com/api/attachment_proxy.php?id=' . urlencode($attachmentId);

// 使用cURL获取附件
$ch = curl_init($h3yunApiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头

// 执行请求
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$curlError = curl_error($ch);
curl_close($ch);

// 检查是否成功
if ($httpCode !== 200 || empty($response)) {
    http_response_code(404);
    echo 'Attachment not found';
    exit;
}

// 分离响应头和响应体
$responseHeader = substr($response, 0, $headerSize);
$responseBody = substr($response, $headerSize);

// 解析Content-Type
preg_match('/Content-Type:\s*([^\r\n]+)/i', $responseHeader, $typeMatches);
$contentType = $typeMatches[1] ?? 'application/octet-stream';

// 解析Content-Disposition获取氚云返回的真实文件名
$filename = 'attachment';
// 支持多种编码格式：RFC 5987, 标准引号, 无引号
if (preg_match('/Content-Disposition:.*filename\*=([^;\r\n]+)/i', $responseHeader, $matches)) {
    $encodedFilename = trim($matches[1]);
    // 解析 charset''encoded-value 格式
    if (preg_match("/^([^']*)'([^']*)'(.+)$/", $encodedFilename, $parts)) {
        $charset = strtoupper($parts[1]);
        $encodedValue = $parts[3];
        $filename = urldecode($encodedValue);
        // 如果字符集不是UTF-8，尝试转换
        if ($charset && $charset !== 'UTF-8' && function_exists('mb_convert_encoding')) {
            $filename = mb_convert_encoding($filename, 'UTF-8', $charset);
        }
    } else {
        $filename = urldecode($encodedFilename);
    }
} elseif (preg_match('/Content-Disposition:.*filename="([^"]+)"/i', $responseHeader, $matches)) {
    $filename = $matches[1];
    if (strpos($filename, '%') !== false) {
        $filename = urldecode($filename);
    }
    // 尝试修复字符编码问题
    if (function_exists('mb_check_encoding') && !mb_check_encoding($filename, 'UTF-8')) {
        if (function_exists('mb_convert_encoding')) {
            $filename = mb_convert_encoding($filename, 'UTF-8', 'GBK');
        }
    }
} elseif (preg_match('/Content-Disposition:.*filename=([^;\r\n]+)/i', $responseHeader, $matches)) {
    $filename = trim($matches[1], '"\' ');
    if (strpos($filename, '%') !== false) {
        $filename = urldecode($filename);
    }
    // 尝试修复字符编码问题
    if (function_exists('mb_check_encoding') && !mb_check_encoding($filename, 'UTF-8')) {
        if (function_exists('mb_convert_encoding')) {
            $filename = mb_convert_encoding($filename, 'UTF-8', 'GBK');
        }
    }
}

// 清理BOM和特殊字符
$filename = preg_replace('/^\xEF\xBB\xBF/', '', $filename);
$filename = trim($filename);

// 如果仍然没有文件名，使用默认值
if ($filename === 'attachment' || empty($filename)) {
    $filename = 'attachment_' . substr($attachmentId, 0, 8);
}

// 返回附件
header('Content-Type: ' . $contentType);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: public, max-age=3600'); // 缓存1小时
header('Content-Length: ' . strlen($responseBody));

echo $responseBody;

// 注意：不再需要 MIME 类型映射函数
// 氚云API已经返回完整的文件名（含扩展名）和正确的Content-Type
